import {
  createSlice,
  createAsyncThunk,
  createEntityAdapter,
  createSelector,
} from "@reduxjs/toolkit";
import axios from "axios";

export const TODOS_FEATURE_KEY = "todos";

export const loadTodos = createAsyncThunk(
  "todos/loadTodos",
  // 方式一：
  // (payload, { dispatch }) => {
  //   axios.get(payload).then(response => dispatch(setTodos(response.data)));
  // }
  // 方式二：
  (payload) => axios.get(payload).then((response) => response.data)
);

const todosAdapter = createEntityAdapter();

const { reducer: TodosReducer, actions } = createSlice({
  name: TODOS_FEATURE_KEY, // 指定状态名字
  // initialState: [], // 指定状态初始值
  initialState: todosAdapter.getInitialState(), // 指定状态初始值
  reducers: {
    // action reducer函数
    // addTodo: (state, action) => {
    //   // state.push(action.payload);
    //   todosAdapter.addOne(state, action.payload)
    // },
    // setTodos: (state, action) => {
    //   // action.payload.forEach((todo) => state.push(todo));
    //   todosAdapter.addMany(state, action.payload)
    // },
    // 改写后
    addTodo: todosAdapter.addOne,
    setTodos: todosAdapter.addMany,
  },
  extraReducers: {
    // reduxjstoolkit执行异步操作方式二
    // [loadTodos.fulfilled]: (state, action) => {
    //   // action.payload.forEach((todo) => {
    //   //   state.push(todo);
    //   // });
    //   todosAdapter.addMany(state, action.payload)
    // },
    [loadTodos.fulfilled]: todosAdapter.addMany,
  },
});

const { selectAll } = todosAdapter.getSelectors();

// 选择器
export const selectTodosList = createSelector(
  (state) => state[TODOS_FEATURE_KEY],
  selectAll
);

export const { addTodo, setTodos } = actions;

// 导出reducer
export default TodosReducer;
